package tom.vertx.core.demo07;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager;
import lombok.extern.slf4j.Slf4j;

/**
 * shareData可以在同一个应用、同一个vertx实例多个verticle之间，集群vertx实例间共享数据(集群依赖cluster manager)
 *    localXXX: 同应用多verticle实例间共享
 *    asyncXXX: 集群内多vertx实例节点间数据共享
 *
 *    集群计数器、本地计数器
 * @author ZHUFEIFEI
 */
@Slf4j
public class ShareData04CounterDemo {

  public static void main(String[] args) {
    //本地zk
    Vertx.clusteredVertx(new VertxOptions().setClusterManager(new ZookeeperClusterManager()), res -> {
      if (res.succeeded()) {
        res.result().deployVerticle(new V1());
        log.info("vertx cluster started.");
      } else {
        log.error("vertx cluster failed.");
      }
    });
  }

  static class V1 extends AbstractVerticle {
    @Override
    public void start(Promise<Void> startPromise) throws Exception {

      vertx.setPeriodic(2000L, id -> {
        log.info("tick tock.");
        //集群中获取计数器，全局增加减少操作
        vertx.sharedData().getCounter("clusterCounter", res -> {
          if (res.succeeded()) {
            res.result().getAndIncrement(rs -> {
              if (rs.succeeded()) {
                log.info("cluster getAndIncrement => {}", rs.result());
              } else {
                log.info("cluster getAndIncrement error => {}", rs.cause().toString());
              }
            });
          } else {
            log.info("cluster getCounter error => {}", res.cause().toString());
          }
        });

      });

      vertx.sharedData().getLocalCounter("myLocalCounter", res -> {
        if (res.succeeded()) {
          res.result().getAndIncrement(rs -> {
            if (rs.succeeded()) {
              log.info("local getAndIncrement => {}", rs.result());
            } else {
              log.info("local getAndIncrement error => {}", rs.cause().toString());
            }
          });
        } else {
          log.info("local getCounter error => {}", res.cause().toString());
        }
      });

      startPromise.complete();
    }
  }

}
